//
//  WMConfirmFixViewController.swift
//  deWaterMarkingProject
//
//  Created by admin on 2025/9/11.
//

import UIKit
import PhotosUI
import Alamofire

class WMConfirmFixViewController: WMBaseViewController {
    
    
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var imageViewWidthConstraint: NSLayoutConstraint!
    @IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
    
    
    var image: UIImage?
    var afterImage: UIImage?
    
    
    var API_KEY = ""
    let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/external/watermark-remove"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.imageView.image = image
        updateImageViewSize()
        customNavBar.setTitle("确认消除")
        // 添加右侧按钮
//        customNavBar.addRightButton(title: "举报", tintColor:UIColor(valueRGB: UInt(OEMInfo.themeHex), alpha: 1.0), target: self, action: #selector(rightButtonClicked))
    }
    
    @objc private func rightButtonClicked() {
        let vc = WMFeedBackViewController(nibName: "WMFeedBackViewController", bundle: nil)
        navigationController?.pushViewController(vc, animated: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        updateImageViewSize()
    }
    
    //重新按钮点击事件
    @IBAction func replayTapGesture(_ sender: Any) {
        
        //校验权限
        checkAlbunAuthority { granted in
            if (granted) {
                self.callingAlbums()
            }else {
                KBMerPrtmissionView.show(type: .PhotoLibrary)
                return;
            }
        }
        
    }
    
    //裁剪按钮点击事件
    @IBAction func cutOutTapGesture(_ sender: Any) {
        let cropingImageVC = WMCroppingImagesViewController()
        cropingImageVC.popBlock = { image in
            self.image = image
            self.imageView.image = image
            self.updateImageViewSize()
        }
        cropingImageVC.image = self.image
        self.navigationController?.pushViewController(cropingImageVC, animated: true)
    }
    
    //确认修复按你的点击事件
    @IBAction func confirmFixBtnClickAction(_ sender: Any) {
        //调用去修复
        //https://picwish.cn/image-watermark-removal-api-doc
        let member = (UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0) == 1
        let picfree = UserDefaults.standard.value(forKey: UserDefaultsKey.picfree) as? Int ?? 0
        let useCount = UserDefaults.standard.value(forKey: UserDefaultsKey.picxyzTotalUseCount) as? Int ?? 0
        if(!member && useCount >= picfree){
            let vc = WMPaymentCenterController(nibName: "WMPaymentCenterController", bundle: nil)
            navigationController?.pushViewController(vc, animated: true)
        }else{
            //去修复网路请求
            startEraser()
        }
        requestEventSave(title: "确认修复", mode: "确认修复")
    }
    
    func saveImageAndGetPath(image: UIImage) -> String? {
        guard let data = image.pngData() else { return nil }
        
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let fileName = "image_\(Date().timeIntervalSince1970).png"
        let fileURL = documentsDirectory.appendingPathComponent(fileName)
        
        do {
            try data.write(to: fileURL)
            return fileURL.path
        } catch {
            print("Error saving image: \(error)")
            return nil
        }
    }
    
    //弹框+进入下一个页面
    func goToNextPage(){

        let comparisonVC = WMImageComparisonViewController()
        comparisonVC.afterImage = afterImage //修复后图片
        comparisonVC.beforeImage = image //修复前图片
        self.navigationController?.pushViewController(comparisonVC, animated: true)
    }
    
    //调用相册
    func callingAlbums(){
        if #available(iOS 14, *) {
            // iOS 14+ 使用 PHPicker
            var config = PHPickerConfiguration()
            config.selectionLimit = 1 // 选择1张图片
            config.filter = .images   // 只显示图片
            
            let picker = PHPickerViewController(configuration: config)
            picker.delegate = self
            present(picker, animated: true)
        } else {
            // iOS 13及以下使用 UIImagePickerController
            let picker = UIImagePickerController()
            picker.sourceType = .photoLibrary
            picker.delegate = self
            present(picker, animated: true)
        }
    }
    
    // 更新图片视图尺寸
    func updateImageViewSize() {
        guard let image = image else { return }
        
        let targetSize = setImageScale(image: image)
        imageViewWidthConstraint.constant = targetSize.width
        imageViewHeightConstraint.constant = targetSize.height
        
        // 确保图片居中显示
        imageView.contentMode = .scaleAspectFit
        
        // 立即更新布局
        self.view.layoutIfNeeded()
    }
    
    //MARk: 获取图片宽高比
    func setImageScale(image: UIImage)  -> CGSize {
        
        //控件最大尺寸
        let maxWidth = kScreenWidth - 30
        let maxHeight = kScreenHeight - kNaviBarHieght - 150
        
        // 获取图片尺寸（以点为单位的尺寸，考虑屏幕缩放）
        let imageSize = image.size
        let imageAspectRatio = imageSize.width / imageSize.height
        let maxAspectRatio = maxWidth / maxHeight
        
        // 根据宽高比决定拉伸方式
        if imageAspectRatio > maxAspectRatio {
            // 宽图：宽度优先
            let targetWidth = min(imageSize.width, maxWidth)
            let targetHeight = targetWidth / imageAspectRatio
            return CGSize(width: targetWidth, height: targetHeight)
        } else {
            // 高图或方图：高度优先
            let targetHeight = min(imageSize.height, maxHeight)
            let targetWidth = targetHeight * imageAspectRatio
            return CGSize(width: targetWidth, height: targetHeight)
        }
        
        
    }
}


// MARK: - PHPickerViewControllerDelegate (iOS 14+)
@available(iOS 14, *)
extension WMConfirmFixViewController: PHPickerViewControllerDelegate {
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        picker.dismiss(animated: true)
        
        guard let result = results.first else { return }
        
        // 加载选中的图片
        result.itemProvider.loadObject(ofClass: UIImage.self) { [weak self] (image, error) in
            DispatchQueue.main.async {
                if let image = image as? UIImage {
                    self?.image = image
                    self?.imageView.image = image
                    self?.updateImageViewSize()
                }
            }
        }
    }
}

// MARK: - UIImagePickerControllerDelegate (iOS 13及以下)
extension WMConfirmFixViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true)
        
        if let image = info[.originalImage] as? UIImage {
            self.image = image
            self.imageView.image = image
            self.updateImageViewSize()
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }
}


extension WMConfirmFixViewController  {
    
    func loadImage(from urlString: String, completion: @escaping (UIImage?) -> Void) {
        guard let url = URL(string: urlString) else {
            completion(nil)
            return
        }
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data, error == nil else {
                completion(nil)
                return
            }
            
            let image = UIImage(data: data)
            DispatchQueue.main.async {
                completion(image)
            }
        }.resume()
    }
    
    /// Begin task
    func startEraser() {
        // 记录每天的解析次数
        var totalCount = UserDefaults.standard.value(forKey: UserDefaultsKey.picxyzTotalUseCount) as? Int ?? 0
        var count = UserDefaults.standard.value(forKey: UserDefaultsKey.picxyzUseCount) as? Int ?? 0
        let maxCount = UserDefaults.standard.value(forKey: UserDefaultsKey.picslimit) as? Int ?? 0
        if count > maxCount {
            showTips(UserDefaults.standard.value(forKey: UserDefaultsKey.picsdesc) as? String ?? "")
            return
        }
        count += 1
        totalCount += 1
        UserDefaults.standard.set(count, forKey: UserDefaultsKey.picxyzUseCount)
        UserDefaults.standard.set(totalCount, forKey: UserDefaultsKey.picxyzTotalUseCount)
        UserDefaults.standard.synchronize()
        showHUD("处理中", "")
        createTask { taskId in
            let startTime = CFAbsoluteTimeGetCurrent()
            self.getTaskResult(taskId: taskId, taskStartTime: startTime) { result in
                print(result)
                self.hideHUD()
                let imageUrl: String = result["image"] as? String ?? ""
                self.loadImage(from: imageUrl) { image in
                    if let image = image {
                        // 使用加载的图片
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
                            self?.afterImage = image
                            self?.goToNextPage()
                        }
                    }
                }
               
                requestEventSave(title: "去水印完成", mode: "auto")
            }
        }
    }

    /// Create a task
    func createTask(completion: @escaping (String) -> Void) {
        let url = URL(string: BASE_URL)!
        API_KEY = UserDefaults.standard.value(forKey: UserDefaultsKey.picxyz) as? String ?? ""
        let headers: HTTPHeaders = [
            "X-API-KEY": API_KEY
        ]
        
        let imagePath = saveImageAndGetPath(image: image!) ?? ""
        
        AF.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(URL(fileURLWithPath: imagePath), withName: "file", fileName: "test.jpg", mimeType: "image/jpeg")
            if let data = "1".data(using: .utf8) {
                multipartFormData.append(data, withName: "output_type")
            }
        }, to: url, method: .post, headers: headers).responseData { response in
            switch response.result {
            case .success(let value):
                if let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
                   let data = json["data"] as? [String: Any],
                   let taskId = data["task_id"] as? String {
                    completion(taskId)
                }
            case .failure(let error):
                self.hideHUD()
                print(error)
            }
        }
    }

    /// Get result
    func getTaskResult(taskId: String,
                       taskStartTime: CFAbsoluteTime,
                       completion: @escaping ([String: Any]) -> Void) {
        let url = URL(string: "\(BASE_URL)/\(taskId)")!
        API_KEY = UserDefaults.standard.value(forKey: UserDefaultsKey.picxyz) as? String ?? ""
        let headers: HTTPHeaders = [
            "X-API-KEY": API_KEY
        ]
        
        AF.request(url, method: .get, headers: headers).responseData { response in
            switch response.result {
                case .success(let value):
                    print(response.debugDescription)
                    guard let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
                          let data = json["data"] as? [String: Any],
                          let state = data["state"] as? Int else {
                        print("parse failed")
                        return
                    }
                    // Task failed, log the details, and exit the loop
                    if state < 0 {
                        print("state < 0")
                        return
                    }
                    //  Task successful
                    if state == 1 {
                        if let imageUrlStr = data["file"] as? String{
                            completion(["image": imageUrlStr])
                            return
                        }
                    }
                          // Retrieve the results by looping only thirty times
                    let endTime = CFAbsoluteTimeGetCurrent()
                    if endTime - taskStartTime < 30 {
                        // Wait for one second between each loop iteration
                        sleep(1)
                        self.getTaskResult(taskId: taskId, taskStartTime: taskStartTime, completion: completion)
                        return
                    }
                    // Timeout, log the details, and search for support from the picwish service
                    print("timeout")
                case .failure(let error):
                    // Request from user server failed. Please record the relevant error logs
                self.hideHUD()
                    print(error)
            }
        }
    }
}


